package com.srd.phone.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.shengrongdai.srd.R;
import com.srd.phone.activity.BorrowSuccessActivity;
import com.srd.phone.activity.DialogLoginActivity;
import com.srd.phone.activity.DialogVerificationActivity;
import com.srd.phone.bean.BarrioInfo;
import com.srd.phone.bean.BorrowPeopleInfo;
import com.srd.phone.bean.ResultInfo;
import com.srd.phone.dialog.BarrioThreeDialog;
import com.srd.phone.dialog.CustomOneDialog;
import com.srd.phone.mvp.presenters.TabBorrowPeoplePresenter;
import com.srd.phone.utils.Constants;
import com.srd.phone.utils.LogUtils;
import com.srd.phone.utils.UserUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 借款 个人
 */
public class TabBorrowPeopleFragment extends BaseFragment implements View.OnClickListener {

    private View viewRoot;
    private EditText et_name, et_number, et_phone, et_check_code, et_street, et_money, et_sketch;
    private Button bt_submit;
    private TextView tv_get_check_code;
    private TextView tv_province, tv_city, tv_district, tv_borrow_type, tv_borrow_value;

    private TabBorrowPeoplePresenter borrowPeoplePresenter;

    private String urlBmarkPersonBorrow = Constants.BASEURL + "bmarkApp/bmarkPersonBorrow"; //获取用户是否注册，登陆
    private String phcode_url = Constants.BASEURL + "loginapp/phCode"; //手机验证码
    private String urlAddPersonApply = Constants.BASEURL + "bmarkApp/addPersonApply"; //提交借款个人信息

    private final int yearTag = 28;
    private final int monthTag = 29;
    private final int dayTag = 30;
    private BarrioInfo province;
    private BarrioInfo city;
    private BarrioInfo district;
    private String[] arrTime = new String[]{"年", "月", "日"};
    private String[] arrYearValue = new String[5];
    private String[] arrMonthValue = new String[60];
    private String[] arrDayValue = new String[30];
    private String selectedType; //借款期限，年月日，
    private String selectedValue; //借款期限，值

    private int isLogin = -1; //是否登录,-1表示未注册，0表示未登录，1表示登录成功
    private boolean isRequest = false; //请求是否发送成功


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        for (int i = 1; i <= 60; i++) {
            if (i < 6) {
                arrYearValue[i - 1] = i + "";
            }
            if (i < 31) {
                arrDayValue[i - 1] = i + "";
            }
            arrMonthValue[i - 1] = i + "";
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (viewRoot == null) {
            viewRoot = getParentView(inflater, container, R.layout.fragment_tab_borrow_people);
            initView();
            initData();
        }
        return viewRoot;
    }

    @Override
    public void initView() {
        et_name = (EditText) viewRoot.findViewById(R.id.et_name);
        et_number = (EditText) viewRoot.findViewById(R.id.et_number);
        et_phone = (EditText) viewRoot.findViewById(R.id.et_phone);
        et_check_code = (EditText) viewRoot.findViewById(R.id.et_check_code);
        et_street = (EditText) viewRoot.findViewById(R.id.et_street);
        et_money = (EditText) viewRoot.findViewById(R.id.et_money);
        et_sketch = (EditText) viewRoot.findViewById(R.id.et_sketch);
        tv_province = (TextView) viewRoot.findViewById(R.id.tv_province);
        tv_city = (TextView) viewRoot.findViewById(R.id.tv_city);
        tv_district = (TextView) viewRoot.findViewById(R.id.tv_district);
        tv_borrow_type = (TextView) viewRoot.findViewById(R.id.tv_borrow_type);
        tv_borrow_value = (TextView) viewRoot.findViewById(R.id.tv_borrow_value);
        bt_submit = (Button) viewRoot.findViewById(R.id.bt_submit);
        tv_get_check_code = (TextView) viewRoot.findViewById(R.id.tv_get_check_code);
        tv_get_check_code.setOnClickListener(this);
        tv_province.setOnClickListener(this);
        tv_city.setOnClickListener(this);
        tv_district.setOnClickListener(this);
        tv_borrow_type.setOnClickListener(this);
        tv_borrow_value.setOnClickListener(this);
        bt_submit.setOnClickListener(this);
    }

    @Override
    public void initData() {
        super.initData();
        presenter = new TabBorrowPeoplePresenter(requestQueue, this);
        borrowPeoplePresenter = (TabBorrowPeoplePresenter) presenter;
        setUrlArrs(urlBmarkPersonBorrow);
        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    checkLoginRes(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //验证当前用户是否登陆，是否注册
    private void checkLoginRes(String value) {
        mContext.showWaitingDialog();
        Map<String, String> map = new HashMap<>();
        map.put("phone", value);
        borrowPeoplePresenter.requestData(urlBmarkPersonBorrow, map);
    }

    private void setBorrowPeopleValue(BorrowPeopleInfo info) {
        if (!TextUtils.isEmpty(info.nm) && !TextUtils.isEmpty(info.idCard)) {
            et_name.setText(info.nm);
            et_number.setText(info.idCard);
            et_name.setEnabled(false);
            et_number.setEnabled(false);
        }
        et_street.setText(info.address);
        String[] arrStr = info.aid.split(",");
        if (arrStr == null || arrStr.length == 0) {
            return;
        }
        province = borrowPeoplePresenter.getProviceValue(arrStr[0]);
        city = borrowPeoplePresenter.getCityValue(arrStr[0], arrStr[1]);
        district = borrowPeoplePresenter.getDistrictValue(arrStr[1], arrStr[2]);
        tv_province.setText(province.name);
        tv_city.setText(city.name);
        tv_district.setText(district.name);
    }

    @Override
    public void returnData(String tag, String data) {
        super.returnData(tag, data);
        mContext.cancelWaitingDialog();
        LogUtils.i(TabBorrowPeopleFragment.class, data);
        if (tag == urlBmarkPersonBorrow) { //判断用户是否登陆或者注册过，
            isRequest = true;
            ResultInfo resultInfo = ResultInfo.parse(data);
            if (resultInfo.code == 0) { //用户不存在
                isLogin = -1;
            } else if (resultInfo.code == -1) { //用户存在但没有登录
                isLogin = 0;
                startActivityForResult(new Intent(mContext, DialogLoginActivity.class), 1);
            } else {
                isLogin = 1;
                setBorrowPeopleValue(BorrowPeopleInfo.parse(data));
            }
        } else if (tag == phcode_url) { // 手机验证码
            ResultInfo info = ResultInfo.parse(data);
            Toast.makeText(mContext, info.msg, Toast.LENGTH_SHORT).show();
        } else if (tag == urlAddPersonApply) { //提交数据
            ResultInfo info = ResultInfo.parse(data);
            if (info.code == 0) {
                startActivity(new Intent(mContext, BorrowSuccessActivity.class));
            } else {
                Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onError(String tag, VolleyError error) {
        mContext.cancelWaitingDialog();
        super.onError(tag, error);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_province:
                barrioDialog();
                break;
            case R.id.tv_city:
                barrioDialog();
                break;
            case R.id.tv_district:
                barrioDialog();
                break;
            case R.id.tv_borrow_type:
                deadlineType();
                break;
            case R.id.tv_borrow_value:
                deadlineValue();
                break;
            case R.id.bt_submit:
                submitData();
                break;
            case R.id.tv_get_check_code:
                sendSMScode();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1000) { //验证码验证成功,开始发送短信
            borrowPeoplePresenter.requestMSMCode(phcode_url, et_phone.getText().toString().trim());
            downTimer.start();
            tv_get_check_code.setEnabled(false);
        } else if (resultCode == 2000) {
            Toast.makeText(mContext, "登陆成功", Toast.LENGTH_SHORT).show();
            isLogin = 1;
        }
    }

    CountDownTimer downTimer = new CountDownTimer(1000 * 60, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tv_get_check_code.setText("剩余" + millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            tv_get_check_code.setEnabled(true);
            tv_get_check_code.setText("重新获取");
        }
    };

    //发送短信验证码
    private void sendSMScode() {
        String phone = et_phone.getText().toString().trim();
        String alert = null;
        if (TextUtils.isEmpty(phone)) {
            alert = "手机号码不能为空";
            Toast.makeText(mContext, alert, Toast.LENGTH_SHORT).show();
        } else if (!borrowPeoplePresenter.checkPhone(phone)) {
            alert = "手机号码不存在";
            Toast.makeText(mContext, alert, Toast.LENGTH_SHORT).show();
        } else {
            startActivityForResult(new Intent(mContext, DialogVerificationActivity.class), 1);
        }
    }

    /**
     * 地址的dialog
     */
    private void barrioDialog() {
        BarrioThreeDialog dialog = BarrioThreeDialog.makeThreeDialog(mContext, new BarrioThreeDialog.OnAddressCListener() {
            @Override
            public void onClick(BarrioInfo province0, BarrioInfo city0, BarrioInfo district0) {
                province = province0;
                city = city0;
                district = district0;
                tv_province.setText(province.name);
                tv_city.setText(city.name);
                tv_district.setText(district.name);
            }
        });
        dialog.show();
    }

    /**
     * 期限，年月日
     */
    private void deadlineType() {
        CustomOneDialog dialog = CustomOneDialog.makeDialog(mContext, arrTime, new CustomOneDialog.OnAddressCListener() {
            @Override
            public void onClick(String value) {
                if (value.equals("年")) {
                    selectedType = "28";
                } else if (value.equals("月")) {
                    selectedType = "29";
                } else if (value.equals("日")) {
                    selectedType = "30";
                }
                tv_borrow_type.setText(value);
                tv_borrow_value.setText("请选择");
                selectedValue = "";
            }
        });
        dialog.show();
    }

    /**
     * 期限值
     */
    private void deadlineValue() {
        if (TextUtils.isEmpty(selectedType)) {
            Toast.makeText(mContext, "请选择借款期限", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] values = null;
        if ("28".equalsIgnoreCase(selectedType)) {
            values = arrYearValue;
        } else if ("29".equalsIgnoreCase(selectedType)) {
            values = arrMonthValue;
        } else if ("30".equalsIgnoreCase(selectedType)) {
            values = arrDayValue;
        }
        CustomOneDialog dialog = CustomOneDialog.makeDialog(mContext, values, new CustomOneDialog.OnAddressCListener() {
            @Override
            public void onClick(String value) {
                selectedValue = value;
                tv_borrow_value.setText(value);
            }
        });
        dialog.show();
    }

    private void submitData() {
        String phone = et_phone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(mContext, "手机号码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isRequest) {
            checkLoginRes(phone);
            return;
        }
        if (isLogin == 0) { //表示未登陆
            startActivityForResult(new Intent(mContext, DialogLoginActivity.class), 1);
            return;
        }

        String name = et_name.getText().toString();
        String card = et_number.getText().toString();
        String checkNum = et_check_code.getText().toString();
        String street = et_street.getText().toString();
        String money = et_money.getText().toString();
        String sketch = et_sketch.getText().toString();
        String value = borrowPeoplePresenter.checkEmpty(name, card, phone, checkNum, money, sketch);
        if (!TextUtils.isEmpty(value)) {
            Toast.makeText(mContext, value, Toast.LENGTH_SHORT).show();
            return;
        }
        if (province == null || city == null || district == null) {
            Toast.makeText(mContext, "地址不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(selectedType) || TextUtils.isEmpty(selectedValue)) {
            Toast.makeText(mContext, "借款期限不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String aid = province.id + "," + city.id + "," + district.id;
        String timetp = "";
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("rid", "");
        map.put("regid", "4");
        map.put("vc", checkNum);
        map.put("code", "");
        map.put("idCard", card);
        map.put("aid", aid);
        map.put("addres", street);
        map.put("term", selectedValue);
        map.put("timetp", selectedType);
        map.put("moneyApply", money);
        map.put("details", sketch);
        if (isLogin == -1) { //表示未注册

        } else if (isLogin == 1) { //表示已经登陆
            map.put("nm", UserUtils.getUserInfo().userName);
            map.put("pwd", UserUtils.getUserInfo().pwd);
        }
        borrowPeoplePresenter.requestData(urlAddPersonApply, map);
    }
}
